package luke4fun.wheresmymoney.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import luke4fun.wheresmymoney.DoAccActivity;
import luke4fun.wheresmymoney.R;
import luke4fun.wheresmymoney.common.CommonConstants;

public class HistoryFragment extends Fragment implements OnPageChangeListener {
	
	private View layout;
	
	private HistoryFragmentPagerAdapter fragmentPagerAdapter;
	private ViewPager mViewPager;
	
	private int pageIndex = 2;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout = inflater.inflate(R.layout.fragment_history, container, false);
		
		fragmentPagerAdapter = new HistoryFragmentPagerAdapter(getChildFragmentManager());
		mViewPager = (ViewPager) layout.findViewById(R.id.pager);
		mViewPager.setAdapter(fragmentPagerAdapter);
		mViewPager.setOnPageChangeListener(this);
		mViewPager.setCurrentItem(pageIndex);
		mViewPager.setOffscreenPageLimit(3);
		
		setHasOptionsMenu(true);
		return layout;
	}

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(getString(R.string.title_history));
    }
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_search, menu);
		inflater.inflate(R.menu.menu_add, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_add_new:
				Intent intent = new Intent(getActivity(), DoAccActivity.class);
				startActivity(intent);
				break;
			case R.id.menu_search:
				break;
		}
		return true;
	}
	
	@Override
	public void onPageScrollStateChanged(int state) {
		if (state == ViewPager.SCROLL_STATE_IDLE) {
			boolean changed = false;
			if (pageIndex == 0) {
				changed = fragmentPagerAdapter.move(CommonConstants.SHIFT_RIGHT);
			} else if (pageIndex == fragmentPagerAdapter.getCount()-1) {
				changed = fragmentPagerAdapter.move(CommonConstants.SHIFT_LEFT);
			}
			
			if (changed) {
				mViewPager.removeAllViews();
				fragmentPagerAdapter.notifyDataSetChanged();
				mViewPager.setCurrentItem(1, false);
			}
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
	}

	@Override
	public void onPageSelected(int position) {
		pageIndex = position;
	}
}
